﻿using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using Logger = KC.Logging.Logger;

namespace KC.Business.Graphics
{
	public class Management
	{
		/// <summary>Creates a thumbnail of a given image.</summary>
		/// <param name="inFile">Fully qualified path to file to create a thumbnail of</param>
		/// <param name="outFile">Fully qualified path to created thumbnail</param>
		/// <param name="x">Width of thumbnail</param>
		/// <returns>flag; result = is success</returns>
		public static bool CreateThumbnail(string inFile, string outFile, int x)
		{
			// Validation - assume 16x16 icon is smallest useful size. Smaller than that is just not going to do us any good 
			// anyway. I consider that an "Exceptional" case. I have not specified a maximum size as some of my panoramas get 
			// *freaking huge*. Have broken the 6-digits-wide barrier.
			if (string.IsNullOrEmpty(inFile)) throw new ArgumentNullException("inFile");
			if (string.IsNullOrEmpty(outFile)) throw new ArgumentNullException("outFile");
			if (x < 16) throw new ArgumentOutOfRangeException("x");
			if (!File.Exists(inFile)) throw new FileNotFoundException("inFile", "File does not exist: " + inFile);

			// Mathematically determine Y dimension
			int y;
			using (Image img = Image.FromFile(inFile))
				y = (int)((double)img.Height * ((double)x / (double)img.Width));

			// All this crap could have easily been Image.Save(filename, x, y)... but nooooo....
			using (Bitmap bmp = new Bitmap(inFile))
			using (Bitmap thumb = new Bitmap((Image)bmp, new Size(x, y)))
			using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(thumb))
			{
				g.SmoothingMode = SmoothingMode.HighQuality;
				g.InterpolationMode = InterpolationMode.High;
				g.CompositingQuality = CompositingQuality.HighQuality;
				ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[1];
				EncoderParameters ep2 = new EncoderParameters(1);
				ep2.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
				g.DrawImage(bmp, new Rectangle(0, 0, thumb.Width, thumb.Height));
				try
				{
					thumb.Save(outFile, codec, ep2);
					return true;
				}
				catch (Exception ex) {
					Logger.LogError(Logger.Project.KcArchitecture, Logger.ErrorLevel.Error, ex.ToString());
					return false; 
				}
			}
		}

	}
}
